package com.woniu.server.service.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.common.utils.PageData;
import com.woniu.common.utils.ResponseData;
import com.woniu.server.dto.*;
import com.woniu.server.feign.CustomerFeign;
import com.woniu.server.feign.UumsFeign;
import com.woniu.server.feign.WorkFeign;
import com.woniu.server.mapper.ProjectApplicationMapper;
import com.woniu.server.pojo.*;
import com.woniu.server.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;


/**
 * @author a
 * @description 针对表【project_application(项目申请表)】的数据库操作Service实现
 * @createDate 2024-11-23 11:53:32
 */
@Service
public class ProjectApplicationServiceImpl extends ServiceImpl<ProjectApplicationMapper, ProjectApplication>
        implements ProjectApplicationService {
    @Autowired
    private CustomerFeign customerFeign;
    @Autowired
    private ApplicationProductService applicationProductService;
    @Autowired
    private ProjectApplicationMapper projectApplicationMapper;
    @Autowired
    private ApprovalRecordService approvalRecordService;
    @Autowired
    private ProjectDetailService projectDetailService;
    @Autowired
    private ProjectProductService projectProductService;
    @Autowired
    private ProjectStorageService projectStorageService;
    @Autowired
    private WorkFeign workFeign;
    @Autowired
    private UumsFeign uumsFeign;


    @Transactional
    @Override
    public ResponseData<?> addApplication(ApplicationDto applicationDto) {
        CustomerDto customerDto = applicationDto.getCustomerDto();
        ApplicationInfoDto applicationInfoDto = applicationDto.getApplicationInfoDto();
        List<List<ApplicationProjectDto>> twoLists = applicationDto.getTwoLists();
        List<ApplicationProjectDto> projectDtoList1 = twoLists.get(0);
        List<ApplicationProjectDto> projectDtoList2 = twoLists.get(1);

        //部署流程(返回部署id)
        String bpmnFile = "ProjectApplication.bpmn20.xml";
        ResponseData<String> responseData1 = workFeign.deployFlow(bpmnFile);
        //启动流程实例(返回流程实例唯一id)
        ResponseData<String> responseData2 = workFeign.startProcess(responseData1.getData());

        //申请信息
        ProjectApplication projectApplication = new ProjectApplication();
        //如果第一个集合不为null，那么就说明不是第一次添加
        String projectApplicationCode;
        if (!Objects.isNull(projectDtoList1) && !projectDtoList1.isEmpty()) {
            projectApplicationCode = projectDtoList1.get(0).getProjectApplicationCode();
            //保存该申请的产品信息
            applicationProductService.addApplicationProductByApplicationCode(projectApplicationCode,
                    applicationInfoDto.getApplicationCode(),
                    projectDtoList2,
                    responseData2.getData());
            return new ResponseData<>().ok();
        } else {
            projectApplicationCode = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
            projectApplication.setProjectApplicationCode(projectApplicationCode);
            projectApplication.setApplicationCode(applicationInfoDto.getApplicationCode());
            projectApplication.setApplicationName(applicationInfoDto.getApplicationName());
            projectApplication.setCustomerId(customerDto.getCode());
            projectApplication.setCustomerName(customerDto.getCustomerName());
            projectApplication.setStatus(1);
            projectApplication.setCreateBy(applicationInfoDto.getApplicationCode());
            //保存申请表
            save(projectApplication);
            //保存该申请的产品信息
            applicationProductService.addApplicationProductByApplicationCode(projectApplicationCode,
                    applicationInfoDto.getApplicationCode(),
                    projectDtoList2,
                    responseData2.getData());
            return new ResponseData<>().ok();
        }


    }

    /**
     * 查询所有用户
     *
     * @Author hht
     * @Date Create by 2024/11/23 10:00
     */
    @Override
    public ResponseData<?> queryAllCustomer() {
        return customerFeign.queryAll();
    }

    /**
     * 通过客户code查询项目列表
     *
     * @Author hht
     * @Date Create by 2024/11/23 11:03
     */
    @Override
    public ResponseData<?> queryProjectListByCode(String customerCode) {
        List<ProjectApplication> list = lambdaQuery().eq(ProjectApplication::getCustomerId, customerCode)
                .list();
        for (ProjectApplication projectApplication : list) {
            if (projectApplication.getStatus() == 1) {
                List<ApplicationProduct> productList = applicationProductService.queryApplicationProductByApplicationCode(projectApplication.getProjectApplicationCode());
                return new ResponseData<>().ok(productList);
            }
        }
        return new ResponseData<>().ok(null);
    }

    /**
     * 查询所有的申请项目
     *
     * @Author hht
     * @Date Create by 2024/11/25 14:20
     */
    @Override
    public ResponseData<?> queryProjectList(PageData<ProjectInfoDto> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<ProjectInfoDto> list = projectApplicationMapper.queryProjectList(pageData.getParam());
        PageInfo<ProjectInfoDto> pageInfo = new PageInfo<>(list);
        return new ResponseData<>().ok(pageInfo);
    }

    /**
     * 审批
     *
     * @Author hht
     * @Date Create by 2024/11/26 19:20
     */
    @Override
    public ResponseData<?> doApproval(ProjectInfoDto projectInfoDto) {
        //判断审批结果，根据审批人的角色进行具体驳回操作
        //总监驳回就直接pass掉这个项目申请，经理驳回流程跳到总监审批
        //1.工作流审批
        PowerUserDto powerUserDto = uumsFeign.queryByCode(projectInfoDto.getApprovalCode());
        workFeign.completeTask(projectInfoDto.getProcessInstanceId(), projectInfoDto.getApprovalStatus(), powerUserDto.getRoleName());
        //2.更新申请产品表
        ApplicationProduct applicationProduct = applicationProductService.queryApplicationProductByApplicationProductCode(projectInfoDto.getApplicationProductCode());
        //根据审批权限修改表数据，流程走
        if ("总监".equals(powerUserDto.getRoleName())) {
            if(projectInfoDto.getApprovalStatus() == 1) {
                //是总监，同意下一步就是经理
                applicationProduct.setStatus(2);
            } else {
                //不同意就直接驳回
                applicationProduct.setStatus(0);
            }
        } else {
            if(projectInfoDto.getApprovalStatus() == 1) {
                //是经理，同意下一步就是完成
                applicationProduct.setStatus(3);
            } else {
                //不同意就回到总监
                applicationProduct.setStatus(1);
            }
        }
        applicationProductService.updateStatusByCode(applicationProduct);
        // 3.更新审批记录表
        ApprovalRecord approvalRecord = approvalRecordService.queryApprovalRecordByApprovalRecordCode(projectInfoDto.getApprovalRecordCode());
        //添加审批人code和name
        approvalRecord.setApprovalCode(projectInfoDto.getApprovalCode());
        approvalRecord.setApprovalName(projectInfoDto.getApprovalName());
        //修改审批状态
        approvalRecord.setApprovalResult(projectInfoDto.getApprovalStatus());
        approvalRecord.setApprovalComments(projectInfoDto.getApprovalComments());
        approvalRecordService.updateApprovalRecordInfo(approvalRecord);
        // 4.添加审批记录表
        if ("总监".equals(powerUserDto.getRoleName())) {
            //通过有下一流程记录，不通过结束流程，没有流程记录
            if(projectInfoDto.getApprovalStatus() == 1) {
                ApprovalRecord newApprovalRecord = new ApprovalRecord();
                String approvalRecordCode = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
                newApprovalRecord.setApprovalRecordCode(approvalRecordCode);
                newApprovalRecord.setApplicationProductCode(projectInfoDto.getApplicationProductCode());
                newApprovalRecord.setStatus(2);
                newApprovalRecord.setStepOrder(2);
                newApprovalRecord.setApprovalResult(0);
                newApprovalRecord.setProcessInstanceId(projectInfoDto.getProcessInstanceId());
                newApprovalRecord.setCreatedBy(powerUserDto.getCode());
                approvalRecordService.save(newApprovalRecord);
            }
        } else {
            //最后一级（经理）此时通过下一级也没有流程记录，此时生成备案号，产品号，添加产品
            // 拒绝添加新的流程纪录
            if(projectInfoDto.getApprovalStatus() == 2) {
                // 拒绝添加新的流程纪录
                ApprovalRecord newApprovalRecord = new ApprovalRecord();
                String approvalRecordCode = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
                newApprovalRecord.setApprovalRecordCode(approvalRecordCode);
                newApprovalRecord.setApplicationProductCode(projectInfoDto.getApplicationProductCode());
                newApprovalRecord.setStatus(1);
                newApprovalRecord.setStepOrder(1);
                newApprovalRecord.setApprovalResult(0);
                newApprovalRecord.setProcessInstanceId(projectInfoDto.getProcessInstanceId());
                newApprovalRecord.setCreatedBy(powerUserDto.getCode());
                approvalRecordService.save(newApprovalRecord);
            } else {
                // 同意，审批结束
                //生成备案号，修改申请表，
                String recordNumber = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
                lambdaUpdate()
                        .eq(ProjectApplication::getProjectApplicationCode, projectInfoDto.getProjectApplicationCode())
                        .set(ProjectApplication::getRecordNumber, recordNumber)
                        .update();
                // 添加项目详情表，
                ProjectDetail projectDetail = new ProjectDetail();
                projectDetail.setRecordNumber(recordNumber);
                String projectCode = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
                projectDetail.setProjectCode(projectCode);
                projectDetail.setCreatedBy(powerUserDto.getCode());
                projectDetailService.save(projectDetail);
                // 生成产品code，修改申请产品表，
                String productCode = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
                ApplicationProduct applicationProduct1 = applicationProductService.queryApplicationProductByApplicationProductCode(projectInfoDto.getApplicationProductCode());
                applicationProduct1.setProductCode(productCode);
                applicationProduct1.setUpdatedBy(powerUserDto.getCode());
                applicationProductService.updateProductCodeByCode(applicationProduct1);
                // 添加新的产品，
                ProjectProduct projectProduct = new ProjectProduct();
                projectProduct.setRecordNumber(recordNumber);
                projectProduct.setProjectName(applicationProduct1.getProjectName());
                projectProduct.setProjectType(applicationProduct1.getProjectType());
                projectProduct.setProductCode(productCode);
                projectProduct.setProductName(applicationProduct1.getProductName());
                projectProduct.setProductMaterial(applicationProduct1.getProductMaterial());
                projectProduct.setProductDescription(applicationProduct1.getProductDescription());
                //生成库存code
                String stockCode = String.valueOf(IdUtil.getSnowflake(1, 1).nextId());
                projectProduct.setStockCode(stockCode);
                projectProduct.setStatus(1);
                projectProduct.setPrice(applicationProduct1.getSellPrice());
                projectProduct.setCreatedBy(powerUserDto.getCode());
                projectProductService.save(projectProduct);
                // 添加库存
                ProjectStorage projectStorage = new ProjectStorage();
                projectStorage.setStorageCode(stockCode);
                projectStorage.setProductCode(productCode);
                projectStorage.setQuantity(1000);
                projectStorage.setReservedQuantity(0);
                projectStorage.setAvailableQuantity(1000);
                projectStorage.setStatus(0);
                projectStorage.setCreatedBy(powerUserDto.getCode());
                projectStorageService.save(projectStorage);
            }
        }
        return new ResponseData<>().ok();
    }
}




